#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$

import logging


class Consumer(object):
    def __init__( self, hierarchy=None, input_channel=None, topic="#" ):
        self.__hierarchy = hierarchy
        self.__topic = topic
        self.__input_channel = input_channel
        if input_channel is not None:
            input_channel.subscribe( topic, self.handleEvent )
            logging.info( "Subscribed %s with topic '%s' to channel %s" % (type( self ).__name__, topic, input_channel.url ) )

    def getHierarchy( self ):
        return self.__hierarchy

    def handleEvent( self, metric, topic=None ):
        import sys
        _function = sys._getframe().f_code.co_name
        _type = type( self )
        raise NotImplementedError( "%s must be overridden in subclass of type %s" % (_function, _type) )

    def unsubscribe( self ):
        if self.__input_channel is not None:
            self.__input_channel.unsubscribe( self.__topic, self.handleEvent )
            logging.info( "Unsubscribed from channel %s with topic '%s'" % (self.__topic, self.__input_channel ) )
